import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
from typing import List, Dict
from .logger import get_logger
from .config import config

logger = get_logger(__name__)

class EmailSender:
    """邮件发送工具类"""
    
    def __init__(self):
        self.smtp_server = config.get('notification.email.smtp_server')
        self.smtp_port = config.get('notification.email.smtp_port')
        self.username = config.get('notification.email.username')
        self.password = config.get('notification.email.password')
        self.from_addr = config.get('notification.email.from_addr')
        self.to_addrs = config.get('notification.email.to_addrs', [])

    def send_convertible_bond_notification(self, bonds: List[Dict]) -> bool:
        """发送可转债申购提醒邮件"""
        if not bonds:
            logger.info("No bonds to notify")
            return True

        try:
            # 创建邮件内容
            msg = MIMEMultipart()
            msg['From'] = self.from_addr
            msg['To'] = ', '.join(self.to_addrs)
            msg['Subject'] = f'可转债申购提醒 - {datetime.now().strftime("%Y-%m-%d")}'

            # 构建HTML内容
            html_content = """
            <html>
            <head>
                <style>
                    table {
                        border-collapse: collapse;
                        width: 100%;
                    }
                    th, td {
                        border: 1px solid #ddd;
                        padding: 8px;
                        text-align: left;
                    }
                    th {
                        background-color: #f2f2f2;
                    }
                    tr:nth-child(even) {
                        background-color: #f9f9f9;
                    }
                </style>
            </head>
            <body>
                <h2>今日可申购可转债信息</h2>
                <table>
                    <tr>
                        <th>转债代码</th>
                        <th>转债名称</th>
                        <th>正股代码</th>
                        <th>正股名称</th>
                        <th>申购日期</th>
                        <th>发行价</th>
                        <th>发行规模(亿)</th>
                        <th>评级</th>
                    </tr>
            """

            for bond in bonds:
                html_content += f"""
                    <tr>
                        <td>{bond['bond_code']}</td>
                        <td>{bond['bond_name']}</td>
                        <td>{bond['stock_code']}</td>
                        <td>{bond['stock_name']}</td>
                        <td>{bond['apply_date']}</td>
                        <td>{bond['issue_price']}</td>
                        <td>{bond['issue_size']}</td>
                        <td>{bond['rating']}</td>
                    </tr>
                """

            html_content += """
                </table>
                <p>请及时查看并做好申购准备。</p>
            </body>
            </html>
            """

            msg.attach(MIMEText(html_content, 'html', 'utf-8'))

            # 发送邮件
            with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
                server.starttls()
                server.login(self.username, self.password)
                server.send_message(msg)

            logger.info(f"Successfully sent email notification for {len(bonds)} bonds")
            return True

        except Exception as e:
            logger.error(f"Failed to send email: {e}")
            return False 